import json

from django.http import HttpResponse
from django.shortcuts import render

# render请求
from green import models


def eight(request):
    lineDict = {}

    stations = ['1号线', '2号线', '3号线', '4号线', '5号线', '10号线', '11号线', '12号线', ]
    for oneStation in stations:
        stationName = oneStation[:-2] + "号线"
        stationsData = models.Stations.objects.filter(line=stationName)
        # print(stationsData)
        line = []
        for item in stationsData:
            line.append(item.station)
        line.sort()
        # print(oneStation)
        # print(line)
        lineDict.update({'line' + oneStation[:-2]: line})

    return render(request, 'eight/eight.html', lineDict)
    # return render(request, "three/three.html")


def creatTimeId(timestr):
    year = int(timestr.split(' ', 1)[0].split('/')[0])
    month = int(timestr.split(' ', 1)[0].split('/')[1])
    day = int(timestr.split(' ', 1)[0].split('/')[2])
    hour = int(timestr.split(' ', 1)[1].split(':', 1)[0])
    return year * 1000000 + month * 10000 + day * 100 + hour


def initBigJsonForEight(request):
    stationsData = models.Stations.objects.all()
    workDaysData = models.Workdays.objects.all()
    bigjson = {}

    for it in stationsData:
        print("遍历station=" + str(it.id) + ":" + str(it.station))
        stationName = it.station
        # inStationData = models.Tripstest.objects.filter(instation=stationName)
        inStationData = models.Trips.objects.filter(instation=stationName)
        # print("inStationData")
        # print(inStationData)
        indata = []

        for one in inStationData:
            if one.intime is None:
                continue

            time = one.intime.split('/', 2)[0]+"/"+one.intime.split('/', 2)[1]  # str = '2020/7/15 14:21' -> '2020/7'
            flag = True
            for i in range(len(indata)):
                # 在data列表里寻找存在的time，如果time 存在则++，否则新建一个字典添加到列表
                if time == indata[i]['time']:
                    indata[i]['windSpeed'] += 1
                    flag = False
            # 原来的列表中没有当前time
            if flag:
                oneData = {'time': one.intime.split('/', 2)[0] + "/" + one.intime.split('/', 2)[1], 'windSpeed': 1}
                indata.append(oneData)
            # print("indata为：")
            # print(indata)


        # 根据time进行排序
        indata.sort(key=lambda stu: stu["time"])
        # print(it.station + ":indata为：")
        # print(indata)


        onedict = {'station': stationName, 'indata': indata}
        bigjson[stationName] = onedict

    # 将bigjson保存为文件

    s = json.dumps(bigjson)
    f = open('templates/eight/bigjson.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造bigjson.json成功！")
    return HttpResponse("构造成功！")


def showEight(request):
    stationName = request.GET.get('stationName')
    # print(request.GET.get('stationName'))
    # print(type(request.GET.get('stationName')))

    if stationName is None:

        f = open('templates/eight/showEight.json', 'r', encoding='utf-8')
        person = f.read()
        f.close()
        response = HttpResponse(person, content_type='application/json; charset=utf-8')

        return response
    else:
        datalist = []
        f = open('templates/eight/bigjson.json', 'r', encoding='utf-8')
        bigjson = f.read()
        f.close()
        print("bigjson的类型为：" + str(type(bigjson)))
        bigdict = json.loads(bigjson)
        dict = bigdict[stationName]
        print("bigdict的类型为：" + str(type(bigdict)))

        person = json.dumps(dict, ensure_ascii=False)
        print(person)
        response = HttpResponse(person, content_type='application/json; charset=utf-8')

        return response
        # return HttpResponse(stationName)
